const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(__dirname));

// 数据库初始化
const db = new sqlite3.Database('gantt.db');

db.serialize(() => {
    db.run(`CREATE TABLE IF NOT EXISTS project_data (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        data TEXT NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )`);
});

// API路由
app.get('/api/load', (req, res) => {
    db.get('SELECT data FROM project_data ORDER BY created_at DESC LIMIT 1', (err, row) => {
        if (err) {
            console.error('数据库错误:', err);
            res.status(500).json({ error: '数据库错误' });
        } else if (row) {
            try {
                const data = JSON.parse(row.data);
                res.json(data);
            } catch (parseErr) {
                console.error('JSON解析错误:', parseErr);
                res.status(500).json({ error: '数据格式错误' });
            }
        } else {
            // 返回默认数据
            const defaultData = {
                buildings: [
                    {
                        id: 1,
                        name: "1号宿舍楼",
                        floors: [
                            {
                                id: 101,
                                name: "1层",
                                tasks: [
                                    { id: 1001, name: "地基工程", start: "2025-01-01", end: "2025-01-15", progress: 100 },
                                    { id: 1002, name: "主体结构", start: "2025-01-16", end: "2025-02-15", progress: 80 },
                                    { id: 1003, name: "装修工程", start: "2025-02-16", end: "2025-03-15", progress: 30 },
                                    { id: 1004, name: "验收交付", start: "2025-03-16", end: "2025-03-31", progress: 0 }
                                ]
                            }
                        ]
                    }
                ]
            };
            res.json(defaultData);
        }
    });
});

app.post('/api/save', (req, res) => {
    const data = JSON.stringify(req.body);
    
    db.run('INSERT INTO project_data (data) VALUES (?)', [data], function(err) {
        if (err) {
            console.error('保存失败:', err);
            res.status(500).json({ error: '保存失败' });
        } else {
            console.log('数据已保存，ID:', this.lastID);
            res.json({ success: true, id: this.lastID });
        }
    });
});

// 获取所有数据
app.get('/api/history', (req, res) => {
    db.all('SELECT id, created_at FROM project_data ORDER BY created_at DESC LIMIT 10', (err, rows) => {
        if (err) {
            res.status(500).json({ error: '获取历史记录失败' });
        } else {
            res.json(rows);
        }
    });
});

// 获取特定版本数据
app.get('/api/version/:id', (req, res) => {
    const id = req.params.id;
    db.get('SELECT data FROM project_data WHERE id = ?', [id], (err, row) => {
        if (err) {
            res.status(500).json({ error: '获取版本失败' });
        } else if (row) {
            try {
                const data = JSON.parse(row.data);
                res.json(data);
            } catch (parseErr) {
                res.status(500).json({ error: '数据格式错误' });
            }
        } else {
            res.status(404).json({ error: '版本不存在' });
        }
    });
});

// 健康检查
app.get('/api/health', (req, res) => {
    res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
    console.log('宿舍楼施工工期横道图系统已启动');
});

// 优雅关闭
process.on('SIGINT', () => {
    console.log('\n正在关闭服务器...');
    db.close((err) => {
        if (err) {
            console.error('关闭数据库时出错:', err);
        } else {
            console.log('数据库已关闭');
        }
        process.exit(0);
    });
});